#include "AT24C02.h"

int8_t AT24C02_Write_Byte(uint8_t add , uint8_t byte)
{
    int8_t ack;
    IIC_Start();
    IIC_Send_Byte(W_ADDER);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    IIC_Send_Byte(add);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    IIC_Send_Byte(byte);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    IIC_Stop();
    return 0;
}

int8_t AT24C02_Write_Page(uint8_t add , uint8_t * txbuf)
{
    uint8_t i;
    uint8_t ack;
    
    IIC_Start();
    IIC_Send_Byte(W_ADDER);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    IIC_Send_Byte(add);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    for(i=0;i<8;i++)
    {
        IIC_Send_Byte(txbuf[i]);
        IIC_Wait_Ack(100);
        if(ack!=0)  return -1;
    }
    IIC_Stop();
    return 0;
}

int8_t AT24C02_Read(uint8_t add ,uint8_t * rxbuf,uint16_t len)
{
    uint8_t i;
    uint8_t ack;
    
    IIC_Start();
    IIC_Send_Byte(W_ADDER);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    IIC_Send_Byte(add);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    IIC_Start();
    IIC_Send_Byte(R_ADDER);
    ack=IIC_Wait_Ack(100);
    if(ack!=0)  return -1;
    
    for(i=0;i<len-1;i++)
    {
        rxbuf[i]=IIC_Read_Byte(1);
    }
    rxbuf[len-1] = IIC_Read_Byte(0);
    IIC_Stop();
    return 0;
}
